package com.recycle.system.service.impl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.recycle.common.core.domain.entity.SysUser;
import com.recycle.common.enums.Recyclable;
import com.recycle.common.utils.DateUtils;
import com.recycle.common.utils.SecurityUtils;
import com.recycle.common.utils.StringUtils;
import com.recycle.common.utils.bean.BeanUtils;
import com.recycle.system.domain.OrderItem;
import com.recycle.system.domain.WasteResource;
import com.recycle.system.domain.dto.NewOrder;
import com.recycle.system.domain.dto.SelectOptions;
import com.recycle.system.domain.vo.ExtendOrder;
import com.recycle.system.mapper.OrderItemMapper;
import com.recycle.system.mapper.WasteResourceMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.recycle.system.mapper.OrderMapper;
import com.recycle.system.domain.Order;
import com.recycle.system.service.IOrderService;

import javax.annotation.Resource;

/**
 * 订单信息Service业务层处理
 *
 * @author recycle
 * @date 2023-03-11
 */
@Service

public class OrderServiceImpl implements IOrderService
{

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private WasteResourceMapper wasteResourceMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    /**
     * 查询订单信息
     *
     * @param orderId 订单信息主键
     * @return 订单信息
     */
    @Override
    public Order selectOrderByOrderId(Long orderId)
    {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    /**
     * 查询订单信息列表
     *
     * @param order 订单信息
     * @return 订单信息
     */
    @Override
    public List<Order> selectOrderList(Order order) {

        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            String userType = SecurityUtils.getLoginUser().getUser().getUserType();
            if (userType.equals("01")) {
                //居民搜索自己发起的申请
                order.setPublisherId(SecurityUtils.getUserId());
            } else {
                //商家搜索向自己发起的申请
                order.setFinisherId(SecurityUtils.getUserId());
            }
        }
        return orderMapper.selectOrderList(order);
    }


    /**
     * 模糊查询订单信息列表
     *
     * @param order 订单信息
     * @return 订单信息集合
     */
    @Override
    public List<Order> fuzzySelectOrderList(Order order)  {
        QueryWrapper wrapper = new QueryWrapper<Order>();
        Field[] fields = Order.class.getDeclaredFields();
        Stream<Field> stream= Arrays.stream(fields);
        stream.forEach(field ->{
            field.setAccessible(true);
            if(field.getType() != String.class){
                return;
            }
            try {
                String value = (String)field.get(order);
                if(("status".equals(value))){
                    value = "`" + value + "`";
                }
                if(StringUtils.isNotEmpty(value)){
                    wrapper.like(field.getName(), value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
        if(StringUtils.isNotEmpty(order.getSearchValue())) {
            wrapper.eq("status",order.getStatus());
        }
        if(!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            String userType = SecurityUtils.getLoginUser().getUser().getUserType();
            if (userType.equals("01")) {
                //居民搜索自己发起的申请
                wrapper.eq("publisher_id", SecurityUtils.getUserId());
            } else {
                //商家搜索向自己发起的申请
                wrapper.eq("finisher_id", SecurityUtils.getUserId());
            }
        }
        return orderMapper.selectList(wrapper);
    }

    /**
     * 新增订单信息
     *
     * @param order 订单信息
     * @return 结果
     */
    @Override
    public int insertOrder(Order order)
    {
        order.setCreateTime(DateUtils.getNowDate());
        return orderMapper.insertOrder(order);
    }

    /**
     * 新增订单(前台)
     *
     * @param order 订单信息
     * @return 结果
     */
    @Override
    public int addOrder(NewOrder order) {
        order.mergeResource();
        //校验居民输入的资源重量是否超过已拥有
        order.getResources().forEach(resource -> {
            QueryWrapper<WasteResource> wrapper = new QueryWrapper<>();
            wrapper.eq("resource_type_id", resource.getResourceTypeId());
            wrapper.eq("owner_id", SecurityUtils.getUserId());
            WasteResource ownResource = wasteResourceMapper.selectOne(wrapper);

            if(resource.getWeight().subtract(ownResource.getWeight())
                    .compareTo(BigDecimal.ZERO) > 0){
                throw new RuntimeException("输入的资源重量超过已拥有资源重量");
        }
        });
        try {
            Order insertOrder = new Order();
            insertOrder.setPublisherId(order.getPublisherId());
            insertOrder.setFinisherId(order.getFinisherId());
            insertOrder.setDescription(order.getDescription());
            insertOrder.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            orderMapper.insertOrder(insertOrder);
            long orderId = insertOrder.getOrderId();

            order.getResources().forEach(resource -> {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(orderId);
                orderItem.setResourceTypeId(resource.getResourceTypeId());
                orderItem.setResourceType(resource.getResourceType());
                orderItem.setWeight(resource.getWeight());
                orderItem.setPrice(resource.getPrice());
                orderItemMapper.insertOrderItem(orderItem);
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 修改订单信息
     *
     * @param order 订单信息
     * @return 结果
     */
    @Override
    public int updateOrder(Order order)
    {
        order.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单信息
     *
     * @param orderIds 需要删除的订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(Long[] orderIds)
    {
        return orderMapper.deleteOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息信息
     *
     * @param orderId 订单信息主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(Long orderId)
    {
        return orderMapper.deleteOrderByOrderId(orderId);
    }



    /**
     * 查询订单关联资源
     *
     * @param orderId 订单信息主键
     * @return 结果
     */
    @Override
    public List<OrderItem> selectRelativeResource(Long orderId) {


        return orderItemMapper.selectOrderItemList(OrderItem.builder().orderId(orderId).build());

    }

    /**
     * 查询商家列表
     *
     * @return 结果
     */
    @Override
    public List<SelectOptions> selectMerchant() {

        return orderMapper.selectMerchant();
    }

    /**
     * 查询历史申请
     *
     * @param order@return 结果
     */
    @Override
    public List<ExtendOrder> selectHistory(ExtendOrder order) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<ExtendOrder> extendOrders  = null;
        if(user.getUserType().equals("01")) {
             extendOrders= orderMapper.selectResidentExtendOrder(user.getUserId());
        }else{
            extendOrders = orderMapper.selectMerchantExtendOrder(user.getUserId());
            extendOrders.forEach(item -> {
                item.negate();
            });
        }
        return extendOrders;
    }
}
